package gobase

import (
	"io"
	"strings"
)

const upperhex = "0123456789ABCDEF"

type encoding int

func shouldEscapeUrl(c byte, mode encoding) bool {
	if 'a' <= c && c <= 'z' || 'A' <= c && c <= 'Z' || '0' <= c && c <= '9' {
		return false
	}

	switch c {
	case '%', '?', '&', '+', '=':
		return true
	default:
		if c >= 0 && c <= 31 {
			return true
		}
		return false
	}
}

// 最简单第一个级别的URL编码
func UrlEncode0(s string) string {
	var sb strings.Builder
	UrlEncode0ToWriter(&sb, s)
	return sb.String()
}

func UrlEncode0ToWriter(w io.Writer, s string) {
	for i := 0; i < len(s); i++ {
		c := s[i]
		if shouldEscapeUrl(c, 0) {
			w.Write([]byte{'%', upperhex[c>>4], upperhex[c&15]})
		} else {
			w.Write([]byte{c})
		}
	}
}
